package com.yhd.tomcat.handler.event;

import com.yhd.tomcat.Bootstrap;
import com.yhd.tomcat.handler.Handler;
import com.yhd.tomcat.handler.service.ServiceHandler;

import java.net.Socket;

/**
 * @author yhd
 * @email yinhuidong1@xiaomi.com
 * @description TODO
 * @since 2021/6/12 上午11:19
 */
public class EventHandler extends Handler {

    private static volatile EventHandler eventHandler;

    private static ServiceHandler serviceHandler=ServiceHandler.getSingleton();

    public static EventHandler getSingleton(){
        if (eventHandler==null){
            synchronized (Bootstrap.class){
                if (eventHandler==null){
                    eventHandler=new EventHandler();
                }
            }
        }
        return eventHandler;
    }

    public void processEvent(){
        System.out.println("EventHandler-->processEvent");
        while (true){
            try {
                if (EVENTQUEUE.size()>0) {
                    Socket socket = EVENTQUEUE.take();
                    System.out.println("从队列中拿到了一个事件任务，交给线程池处理");
                    executor.submit(()-> {
                        try {
                            serviceHandler.process(socket);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private EventHandler() {

    }
}
